/**
 * VillageRenderer - 村庄渲染器
 * 统一管理村庄场景的所有渲染任务
 */

import DrawingEngine from '../pet-renderer/DrawingEngine.js'
import BuildingManager from './BuildingManager.js'
import VillagerManager from './VillagerManager.js'
import ParticleSystem from './ParticleSystem.js'
import WeatherSystem from './WeatherSystem.js'
import DayNightCycle from './DayNightCycle.js'
import InteractionManager from './InteractionManager.js'
import EventVisualizer from './EventVisualizer.js'

class VillageRenderer {
  constructor(ctx, options = {}) {
    this.ctx = ctx
    this.options = {
      width: options.width || 750,
      height: options.height || 1000,
      pixelRatio: options.pixelRatio || 1,
      debugMode: options.debugMode || false
    }
    
    this.drawingEngine = new DrawingEngine(ctx)
    this.buildingManager = new BuildingManager(ctx)
    this.villagerManager = new VillagerManager(ctx)
    this.particleSystem = new ParticleSystem(ctx)
    this.weatherSystem = new WeatherSystem(ctx, {
      width: this.options.width,
      height: this.options.height
    })
    this.dayNightCycle = new DayNightCycle(ctx, {
      width: this.options.width,
      height: this.options.height
    })
    this.interactionManager = new InteractionManager({
      width: this.options.width,
      height: this.options.height,
      camera: this.camera
    })
    this.eventVisualizer = new EventVisualizer(ctx)
    
    // 相机系统
    this.camera = {
      x: 0,
      y: 0,
      zoom: 1
    }
    
    // 网格配置
    this.grid = {
      size: 80, // 每个网格80px
      rows: Math.ceil(this.options.height / 80),
      cols: Math.ceil(this.options.width / 80)
    }
    
    // 缓存
    this.groundCache = null
    this.needsRedraw = true
    
    // 地面装饰
    this.decorations = this.generateDecorations()
  }
  
  /**
   * 生成地面装饰
   */
  generateDecorations() {
    const decorations = []
    
    // 生成树木
    for (let i = 0; i < 15; i++) {
      decorations.push({
        type: 'tree',
        x: Math.random() * this.options.width,
        y: Math.random() * this.options.height,
        size: Math.random() * 20 + 30
      })
    }
    
    // 生成石头
    for (let i = 0; i < 20; i++) {
      decorations.push({
        type: 'rock',
        x: Math.random() * this.options.width,
        y: Math.random() * this.options.height,
        size: Math.random() * 15 + 10
      })
    }
    
    // 生成花朵
    for (let i = 0; i < 30; i++) {
      decorations.push({
        type: 'flower',
        x: Math.random() * this.options.width,
        y: Math.random() * this.options.height,
        size: Math.random() * 10 + 5,
        color: ['#FF6B9D', '#FEC5BB', '#FFF4E6', '#E0ACD5'][Math.floor(Math.random() * 4)]
      })
    }
    
    return decorations
  }

  /**
   * 主渲染方法
   */
  render(sceneData, timestamp) {
    // 清空画布
    this.drawingEngine.clearAll(this.options.width, this.options.height)
    
    // 应用相机变换
    this.drawingEngine.save()
    this.drawingEngine.translate(this.camera.x, this.camera.y)
    this.drawingEngine.scale(this.camera.zoom, this.camera.zoom)
    
    // 绘制地面
    this.drawGround()
    
    // 绘制装饰
    this.drawDecorations()
    
    // 绘制网格（调试模式）
    if (this.options.debugMode) {
      this.drawGrid()
    }
    
    // 绘制建筑
    if (sceneData.buildings && sceneData.buildings.length > 0) {
      this.buildingManager.render(sceneData.buildings, timestamp)
    }
    
    // 绘制拖拽预览
    this.buildingManager.drawDragPreview(this.grid.size)
    
    // 绘制村民
    if (sceneData.buildings && sceneData.buildings.length > 0) {
      this.villagerManager.render(sceneData.villagers, sceneData.buildings, timestamp)
    }
    
    // 绘制粒子效果
    this.particleSystem.render(timestamp)
    
    // 绘制事件可视化
    if (sceneData.events) {
      this.eventVisualizer.render(timestamp)
    }
    
    this.drawingEngine.restore()
    
    // 绘制调试信息
    if (this.options.debugMode) {
      this.drawDebugInfo(timestamp)
    }
  }

  /**
   * 绘制地面
   */
  drawGround() {
    // 绘制草地背景
    const gradient = this.drawingEngine.createLinearGradient(
      0, 0,
      0, this.options.height,
      [
        { offset: 0, color: '#7CB342' },
        { offset: 0.5, color: '#8BC34A' },
        { offset: 1, color: '#9CCC65' }
      ]
    )
    
    this.ctx.setFillStyle(gradient)
    this.ctx.fillRect(0, 0, this.options.width, this.options.height)
    
    // 添加草地纹理（简单的点）
    this.ctx.setFillStyle('rgba(139, 195, 74, 0.3)')
    for (let i = 0; i < 100; i++) {
      const x = Math.random() * this.options.width
      const y = Math.random() * this.options.height
      const size = Math.random() * 3 + 1
      this.ctx.beginPath()
      this.ctx.arc(x, y, size, 0, Math.PI * 2)
      this.ctx.fill()
    }
  }

  /**
   * 绘制装饰
   */
  drawDecorations() {
    this.decorations.forEach(decoration => {
      switch(decoration.type) {
        case 'tree':
          this.drawTree(decoration)
          break
        case 'rock':
          this.drawRock(decoration)
          break
        case 'flower':
          this.drawFlower(decoration)
          break
      }
    })
  }
  
  /**
   * 绘制树木
   */
  drawTree(tree) {
    const { x, y, size } = tree
    
    // 树干
    this.ctx.setFillStyle('#8B4513')
    this.ctx.fillRect(x - size/8, y, size/4, size/2)
    
    // 树冠
    this.ctx.setFillStyle('#2D5016')
    this.ctx.beginPath()
    this.ctx.arc(x, y - size/4, size/2, 0, Math.PI * 2)
    this.ctx.fill()
    
    // 高光
    this.ctx.setFillStyle('rgba(139, 195, 74, 0.5)')
    this.ctx.beginPath()
    this.ctx.arc(x - size/6, y - size/3, size/4, 0, Math.PI * 2)
    this.ctx.fill()
  }
  
  /**
   * 绘制石头
   */
  drawRock(rock) {
    const { x, y, size } = rock
    
    this.ctx.setFillStyle('#808080')
    this.ctx.beginPath()
    this.ctx.arc(x, y, size/2, 0, Math.PI * 2)
    this.ctx.fill()
    
    // 阴影
    this.ctx.setFillStyle('rgba(0, 0, 0, 0.2)')
    this.ctx.beginPath()
    this.ctx.arc(x + size/4, y + size/4, size/2, 0, Math.PI * 2)
    this.ctx.fill()
  }
  
  /**
   * 绘制花朵
   */
  drawFlower(flower) {
    const { x, y, size, color } = flower
    
    // 花瓣
    this.ctx.setFillStyle(color)
    for (let i = 0; i < 5; i++) {
      const angle = (i / 5) * Math.PI * 2
      const petalX = x + Math.cos(angle) * size/2
      const petalY = y + Math.sin(angle) * size/2
      this.ctx.beginPath()
      this.ctx.arc(petalX, petalY, size/3, 0, Math.PI * 2)
      this.ctx.fill()
    }
    
    // 花心
    this.ctx.setFillStyle('#FFD700')
    this.ctx.beginPath()
    this.ctx.arc(x, y, size/4, 0, Math.PI * 2)
    this.ctx.fill()
  }
  
  /**
   * 绘制网格
   */
  drawGrid() {
    this.ctx.setStrokeStyle('rgba(255, 255, 255, 0.2)')
    this.ctx.setLineWidth(1)
    
    // 绘制垂直线
    for (let i = 0; i <= this.grid.cols; i++) {
      const x = i * this.grid.size
      this.ctx.beginPath()
      this.ctx.moveTo(x, 0)
      this.ctx.lineTo(x, this.options.height)
      this.ctx.stroke()
    }
    
    // 绘制水平线
    for (let i = 0; i <= this.grid.rows; i++) {
      const y = i * this.grid.size
      this.ctx.beginPath()
      this.ctx.moveTo(0, y)
      this.ctx.lineTo(this.options.width, y)
      this.ctx.stroke()
    }
  }

  /**
   * 绘制调试信息
   */
  drawDebugInfo(timestamp) {
    const fps = Math.round(1000 / (timestamp - (this.lastTimestamp || timestamp)))
    this.lastTimestamp = timestamp
    
    this.ctx.setFillStyle('rgba(0, 0, 0, 0.7)')
    this.ctx.fillRect(10, 10, 200, 80)
    
    this.ctx.setFillStyle('#fff')
    this.ctx.setFontSize(14)
    this.ctx.fillText(`FPS: ${fps}`, 20, 30)
    this.ctx.fillText(`Camera: (${this.camera.x}, ${this.camera.y})`, 20, 50)
    this.ctx.fillText(`Zoom: ${this.camera.zoom.toFixed(2)}`, 20, 70)
  }

  /**
   * 世界坐标转屏幕坐标
   */
  worldToScreen(x, y) {
    return {
      x: (x + this.camera.x) * this.camera.zoom,
      y: (y + this.camera.y) * this.camera.zoom
    }
  }

  /**
   * 屏幕坐标转世界坐标
   */
  screenToWorld(x, y) {
    return {
      x: x / this.camera.zoom - this.camera.x,
      y: y / this.camera.zoom - this.camera.y
    }
  }

  /**
   * 移动相机
   */
  moveCamera(dx, dy) {
    this.camera.x += dx
    this.camera.y += dy
  }

  /**
   * 设置缩放
   */
  setZoom(zoom) {
    this.camera.zoom = Math.max(0.5, Math.min(2, zoom))
  }

  /**
   * 获取网格位置
   */
  getGridPosition(x, y) {
    return {
      col: Math.floor(x / this.grid.size),
      row: Math.floor(y / this.grid.size)
    }
  }

  /**
   * 网格位置转世界坐标
   */
  gridToWorld(col, row) {
    return {
      x: col * this.grid.size,
      y: row * this.grid.size
    }
  }

  /**
   * 点击检测
   */
  hitTest(x, y, sceneData) {
    // 检测点击的村民（优先，因为村民在上层）
    if (this.villagerManager.villagers && this.villagerManager.villagers.length > 0) {
      const villager = this.villagerManager.hitTest(x, y, this.villagerManager.villagers)
      if (villager) return { type: 'villager', data: villager }
    }
    
    // 检测点击的建筑
    if (sceneData.buildings) {
      const building = this.buildingManager.hitTest(x, y, sceneData.buildings)
      if (building) return { type: 'building', data: building }
    }
    
    return null
  }

  /**
   * 添加资源收集特效
   */
  addResourceCollect(x, y, resourceType) {
    this.particleSystem.addResourceCollect(x, y, resourceType)
  }

  /**
   * 添加升级特效
   */
  addUpgradeEffect(x, y) {
    this.particleSystem.addUpgradeEffect(x, y)
  }

  /**
   * 添加庆祝特效
   */
  addCelebrationEffect(x, y) {
    this.particleSystem.addCelebrationEffect(x, y)
  }

  /**
   * 添加村民
   */
  addVillager(villager) {
    return this.villagerManager.addVillager(villager)
  }

  /**
   * 分配村民职业
   */
  assignVillagerJob(villager, job) {
    this.villagerManager.assignJob(villager, job)
  }

  /**
   * 处理触摸开始
   */
  handleTouchStart(e, sceneData) {
    this.interactionManager.updateCamera(this.camera)
    return this.interactionManager.handleTouchStart(e, sceneData.buildings, sceneData.villagers)
  }

  /**
   * 处理触摸移动
   */
  handleTouchMove(e) {
    const result = this.interactionManager.handleTouchMove(e)
    
    // 处理相机拖拽
    if (result && result.type === 'camera-drag') {
      this.moveCamera(result.delta.x, result.delta.y)
    }
    
    return result
  }

  /**
   * 处理触摸结束
   */
  handleTouchEnd(e) {
    return this.interactionManager.handleTouchEnd(e)
  }

  /**
   * 处理长按
   */
  handleLongPress(e, sceneData) {
    this.interactionManager.updateCamera(this.camera)
    return this.interactionManager.handleLongPress(e, sceneData.buildings, sceneData.villagers)
  }

  /**
   * 检查网格是否可用
   */
  isGridAvailable(gridPos, buildings, excludeBuilding = null) {
    return this.interactionManager.isGridAvailable(gridPos, buildings, excludeBuilding)
  }

  /**
   * 获取最近的可用网格
   */
  getNearestAvailableGrid(worldPos, buildings) {
    return this.interactionManager.getNearestAvailableGrid(worldPos, buildings)
  }

  /**
   * 添加事件
   */
  addEvent(event) {
    return this.eventVisualizer.addEvent(event)
  }

  /**
   * 移除事件
   */
  removeEvent(eventId) {
    this.eventVisualizer.removeEvent(eventId)
  }

  /**
   * 清除所有事件
   */
  clearAllEvents() {
    this.eventVisualizer.clearAll()
  }

  /**
   * 检测事件点击
   */
  hitTestEvent(x, y) {
    return this.eventVisualizer.hitTest(x, y)
  }

  /**
   * 销毁渲染器
   */
  destroy() {
    this.drawingEngine = null
    this.buildingManager = null
    this.villagerManager = null
    this.particleSystem = null
    this.weatherSystem = null
    this.dayNightCycle = null
    this.interactionManager = null
    this.eventVisualizer = null
    this.ctx = null
    this.groundCache = null
  }
}

export default VillageRenderer
